/*
 * @Author: 郑俊标
 * @Date: 2024-06-05 17:15:35
 * @LastEditors: 郑俊标
 * @LastEditTime: 2024-06-21 14:39:00
 * @Description:  
 */
import { login, getInfo, logout } from '@/api/login';
import { setToken, getToken, removeToken } from '@/utils/auth';

const user = {
    state: {
        token: getToken(),
        roles: [],
        permissions: [],
        id: '',
		name: '',
		avatar: '',
    },
    actions: {
        Login({ commit }, payload) {
            return new Promise((resolve, reject) => {
                login(payload)
                    .then((res) => {
                        setToken(res.token);
                        commit('SET_TOKEN', res.token);
                        resolve(res)
                    })
                    .catch((error) => {
                        reject(error);
                    });
            })
        },
        // 获取用户信息
        GetInfo({commit},payload) {
            return new Promise((resolve, reject) => {
                getInfo().then((res) => {
                    const user = res.user;
                    const avatar = user.avatar === '' || user.avatar === null ? require('@/assets/images/profile.jpg') : user.avatar;
                    // 判断用户角色是否为空
                    if (res.roles && res.roles.length > 0) {
                        commit('SET_ROLES', res.roles);
                        commit('SET_PERMISSION', res.permissions);
                    } else {
                        // 没有角色，赋予 默认角色
                        commit('SET_ROLES', ['ROLE_DEFAULT']);
                    }
                    commit('SET_ID', user.userId);
                    commit('SET_NAME', user.userName);
                    commit('SET_AVATAR', avatar);
                    resolve(res);
                }).catch((error) => {
                    reject(error);
                })
            })
        },
        // 退出登录
        LogOut({commit,state}) {
            return new Promise((resolve,reject) => {
                logout(state.token).then(() => {
                    removeToken();
                    commit('SET_TOKEN', '');
                    commit('SET_ROLES', []);
                    commit('SET_PERMISSION', []);
                    resolve();
                }).catch((error) => {
                    reject(error);
                })
            })            
        }
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.toen = token;
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles;
        },
        SET_PERMISSION: (state, permissions) => {
            state.permissions = permissions;
        },
        SET_ID: (state, id) => {
            state.id = id;
        },
        SET_NAME: (state, name) => {
            state.name = name;
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar;
        }
    }
}

export default user;